<?php

class Taoke
{
    private $union;
    public function __construct($union)
    {
        $this->union = $union;
    }
    /**参数加密
     * @param $data
     * @param $appSecret
     * @return string
     */
    private function makeSign($data, $appSecret)
    {
        ksort($data);
        $str = '';
        foreach ($data as $k => $v) {
            $str .= '&' . $k . '=' . $v;
        }
        $str  = trim($str, '&');
        $sign = strtoupper(md5($str . '&key=' . $appSecret));
        return $sign;
    }


    /**
     * @param $host 接口请求地址
     * @param $params 参数
     */
    private function http_request_post($host, $params)
    {
        //接口地址
        $appKey    = $this->union['dtkAppKey'];//应用的key
        $appSecret = $this->union['dtkAppSecret'];//应用的Secret
        //默认必传参数
        $data = [
            'appKey'  => $appKey,
            'version' => isset($params['version']) ? $params['version'] : 'v1.2.3',
        ];
        $data = array_merge($data, $params);
        //加密的参数
        $data['sign'] = $this->makeSign($data, $appSecret);
        //拼接请求地址
        $url = $host . '?' . http_build_query($data);
//        //执行请求获取数据
//        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
//        curl_setopt($ch, CURLOPT_HEADER, 0);
//        $output = curl_exec($ch);
//        curl_close($ch);

        $output = file_get_contents($url);
        return $output ? json_decode($output, true) : [];
    }


    /**
     * @param $data 数据转换
     */
    public function trans_data($data)
    {
        $new_data = [];
        foreach ($data as $key => $value) {
            $new_data[$key]["GoodsId"]       = $value['goodsId'];
            $new_data[$key]["Title"]         = $value["title"];
            $new_data[$key]["ShortTitle"]    = $value['dtitle'];
            $new_data[$key]["ShopType"]      =isset($value['shopType']) ? $value['shopType'] == 1 ? '天猫' : '淘宝' : '天猫';
            $new_data[$key]["PicLogo"]       = $value['mainPic'];
            $new_data[$key]["CouponMoney"]   = $value['couponPrice'];
            $new_data[$key]["Price"]         = $value['originalPrice'];
            $new_data[$key]["EndPrice"]      = $value['actualPrice'];
            $new_data[$key]["MonthSale"]     = $value['monthSales'];
            $new_data[$key]["Site"]          = "haodanku";
            $new_data[$key]["ItemFrom"]      = "taoke";
            $new_data[$key]['VideoUrl']     = isset($value['video']) ? $value['video'] : '';
            $new_data[$key]['Commission']    = ($value['originalPrice']-$value['couponPrice']) * $value['commissionRate'] / 100;
            $new_data[$key]["Couponurl"]     = $value['couponLink'];
            $new_data[$key]["ShopName"]      = isset($value['shopName']) && $value['shopName'] ? $value['shopName'] : '';
            $new_data[$key]["CouponTotal"]   = $value['couponTotalNum'];
            $new_data[$key]["CouponSurplus"] = $value['couponTotalNum'] - $value['couponReceiveNum'];
            $new_data[$key]["IsAd"]          = 0;
        }
        return $new_data;
    }


    /**
     * 9.9包邮精选
     */
    public function opgoodslist($params)
    {
        $url = 'https://openapi.dataoke.com/api/goods/nine/op-goods-list';

        $h_params = [];
        if ($params['page_size']) {
            $h_params['pageSize'] = $params['page_size'];
        } else {
            $h_params['pageSize'] = 10;
        }
        if ($params['page']) {
            $h_params['pageId'] = $params['page'];
        } else {
            $h_params['pageId'] = 1;
        }
        if ($params['cid']) {
            $h_params['Cid'] = $h_params['nineCid'] = $params['cid'];
        } else {
            $h_params['Cid'] = $h_params['nineCid'] = -1;
        };
        ksort($h_params);
        $res = $this->http_request_post($url, $h_params);
        if ($res['code'] == 0) {
            $data = $this->trans_data($res['data']['list']);
            return ['code' => true, 'data' => $data];
        } else {
            return ['code' => false, 'data' => $res['msg']];
        }
    }

    /**
     * 各大榜单API
     * @param $params
     * @return mixed
     */
    public function getrankinglist($params)
    {
        $url      = 'https://openapi.dataoke.com/api/goods/get-ranking-list';
        $h_params = [];

        if (isset($params['cid']) && $params['cid']) {
            $h_params['cid'] = $params['cid'];
        }
        if (isset($params['version']) && $params['version']) {
            $h_params['version'] = $params['version'];
        } else {
            $h_params['version'] = 'v1.2.0';
        }
        if (isset($params['rank']) && $params['rank']) {
            $h_params['rankType'] = $params['rank'];
        } else {
            $h_params['rankType'] = 3;
        }
        $res = $this->http_request_post($url, $h_params);
        if (isset($res['code']) && $res['code'] == 0) {
            $data = $this->trans_data($res['data']);
            return ['code' => true, 'data' => $data];
        } else {
            return ['code' => false, 'data' => $res['msg']];
        }
    }

    /**
     * 9.9包邮精选
     */
    public function getgoodslist($params)
    {
        $url      = 'https://openapi.dataoke.com/api/goods/get-goods-list';
        $h_params = [];
        if (isset($params['page_size']) && $params['page_size']) {
            $h_params['pageSize'] = $params['page_size'];
        } else {
            $h_params['pageSize'] = 10;
        }
        if (isset($params['page']) && $params['page']) {
            $h_params['pageId'] = $params['page'];
        } else {
            $h_params['pageId'] = 1;
        }

        if (isset($params['order_by']) && $params['order_by']) {
            if ($params['order_by'] == 'price' && $params['sort'] == 'asc') {
                $h_params['sort'] = 5;
            }
            if ($params['order_by'] == 'price' && $params['sort'] == 'desc') {
                $h_params['sort'] = 6;
            }
            if ($params['order_by'] == 'sale' && $params['sort'] == 'asc') {
                $h_params['sort'] = 2;
            }
            if ($params['order_by'] == 'commission' && $params['sort'] == 'asc') {
                $h_params['sort'] = 4;
            }
            if ($params['order_by'] == 'moren' && $params['sort'] == 'desc') {
                $h_params['sort'] = 0;
            }
        };
        if (isset($params['brand_ids']) && $params['brand_ids']) {
            $h_params['brandIds'] = $params['brand_ids'];
        }
        if (isset($params['version']) && $params['version']) {
            $h_params['version'] = $params['version'];
        } else {
            $h_params['version'] = 'v1.2.0';
        }
        $res = $this->http_request_post($url, $h_params);
        if (isset($res['code']) && $res['code'] == 0) {
            $data = $this->trans_data($res['data']['list']);
            return ['code' => true, 'data' => $data];
        } else {
            return ['code' => false, 'data' => $res['msg']];
        }
    }


    public function searchsuggestion($params)
    {
        $url                  = "https://openapi.dataoke.com/api/goods/search-suggestion";
        $h_params['keyWords'] = $params['keyWords'];
        $h_params['type']     = $params['type'];
        $res                  = $this->http_request_post($url, $h_params);
        if ($res['code'] == 0) {
            $responseResult = [];
            foreach($res['data'] as $key=>$value){
                $responseResult[]['title'] = $value['kw'];
            }
            return $responseResult;
        } else {
            return [];
        }
    }

    //品牌库API
    public function brand_list($params = [])
    {
        $url      = "https://openapi.dataoke.com/api/tb-service/get-brand-list";
        $h_params = [];
        if ($params['page_size']) {
            $h_params['pageSize'] = $params['page_size'];
        } else {
            $h_params['pageSize'] = 10;
        }
        if ($params['page']) {
            $h_params['pageId'] = $params['page'];
        } else {
            $h_params['pageId'] = 1;
        }
        $h_params['version'] = 'v1.1.1';
        $res                 = $this->http_request_post($url, $h_params);


//        var_dump($res);
//        exit;
        if ($res['code'] == 0) {
            return $res['data'];
        } else {
            return [];
        }

    }


    //限时抢购
    public function ddq_goods_list($time='')
    {
        $url      = "https://openapi.dataoke.com/api/category/ddq-goods-list";
        $h_params = [];

        $h_params['roundTime'] = $time;
        $h_params['version']   = 'v1.2.1';
        $res                   = $this->http_request_post($url, $h_params);
        $list = [];
        if(isset($res['data']['goodsList']) && !empty($res['data']['goodsList'])){
            $list = $this->trans_data($res['data']['goodsList']);
        }
        return $list;

    }


    /*
     * 大淘客每日爆品
     * https://www.dataoke.com/kfpt/api-d.html?id=34
     */
    public function explosive_goods_list($params){
        $url      = "https://openapi.dataoke.com/api/goods/explosive-goods-list";
        $h_params = [];
        if ($params['page_size']) {
            $h_params['pageSize'] = $params['page_size'];
        } else {
            $h_params['pageSize'] = 10;
        }
        if ($params['page']) {
            $h_params['pageId'] = $params['page'];
        } else {
            $h_params['pageId'] = 1;
        }
        $h_params['version'] = 'v1.1.1';
        $res                 = $this->http_request_post($url, $h_params);
        if ($res['code'] == 0) {
            $trun_data = $this->trans_data($res['data']['list']);
            return $trun_data;
        } else {
            return [];
        }
    }


    /**
     * https://www.dataoke.com/kfpt/api-d.html?id=80
     * 大淘客拼多多商品解析
     */
    public function contentParse($keywords){
        $url = 'https://openapi.dataoke.com/api/dels/kit/contentParse';
        $h_params['content'] = $keywords;
        $responseMsg = $this->http_request_post($url, $h_params);
        if (isset($responseMsg['code']) && $responseMsg['code'] == 0) {
            if(isset($responseMsg['data']['platType'])){
                if($responseMsg['data']['platType'] == 'pdd'){
                    $src = 3;
                }elseif ($responseMsg['data']['platType'] == 'jd'){
                    $src = 2;
                }elseif ($responseMsg['data']['platType'] == 'taobao'){
                    $src = 1;
                }else{
                    return ['status' => false, 'goodsId' => '', 'msg' => '解析失败'];
                }
                return ['status' => true, 'goodsId' => $responseMsg['data']['itemId'],'src'=>$src, 'msg' => '解析成功'];
            }else{
                return ['status' => false, 'goodsId' => '', 'msg' => '解析失败'];
            }
        }else{
            return ['status' => false, 'goodsId' => '', 'msg' => '解析失败'];
        }
    }


    /**
     * https://www.dataoke.com/kfpt/api-d.html?id=33
     * 解析淘口令
     */
    public function parsecontent($content)
    {
        $url = "https://openapi.dataoke.com/api/tb-service/parse-content";
        $params['content'] = $content;
        $responseMsg = $this->dataSign($url, $params);
        $responseData = ['status' => false, 'msg' => '解析失败', 'goodsId' => ''];
        if (isset($responseMsg['code']) && $responseMsg['code'] == 0) {
            $responseData['goodsId'] = $responseMsg['data']['itemId'];
            $responseData['status'] = true;
        }
        return $responseData;
    }



}
